#include "treebuilder.h"

#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QSqlQuery>
#include <QDebug>
#include <QScriptContext>
#include <scriptmanager.h>
#include <QtGui>


QScriptValue treeBuilderConstructor(QScriptContext *context, QScriptEngine *engine)
{
    QTreeWidget* treeWidget = qobject_cast<QTreeWidget*>(context->argument(0).toQObject());
    QString dbName = context->argument(1).toString();

    QSqlDatabase db = QSqlDatabase::database(dbName);

    SqlTreeBuilder* sb = new SqlTreeBuilder(treeWidget, db);

    return engine->newQObject(sb, QScriptEngine::ScriptOwnership);
}

SqlTreeBuilder::SqlTreeBuilder(QTreeWidget *tree, QSqlDatabase &db) :
    QObject(0),
    m_db(db),
    m_treeWidget(tree)
{
    m_query = new QSqlQuery(db);
}

SqlTreeBuilder::SqlTreeBuilder(QSqlDatabase &db, QTreeWidget *tree, const QString &tableName, const QString &nameField, const QString &codeField, const QStringList &pattern) :
    QObject(0),        
    m_tableName(tableName),
    m_nameField(nameField),
    m_codeField(codeField),
    m_pattern(pattern),
    m_db(db),
    m_treeWidget(tree)
{
    m_query = new QSqlQuery(db);
}

SqlTreeBuilder::~SqlTreeBuilder()
{
    delete m_query;
}

void SqlTreeBuilder::build()
{
    if(m_treeWidget != 0)
    {
        m_treeWidget->clear();
        if( m_query->prepare("select " + m_codeField + ", " + m_nameField + " from "+m_tableName+" where " + m_codeField + " like ?") )
            recursion();
    }
}

void SqlTreeBuilder::recursion(int level, QTreeWidgetItem *parent)
{
    QString likePattern;
    QString parentData;

    if(parent != 0)
        parentData = parent->data(0, Qt::WhatsThisRole).toString();

    int totalLen = 0;
    for( int i = 0; i < m_pattern.size(); i++ ) {
        int len = m_pattern.at(i).toInt();
        totalLen += len;
        if( i > level ) {
            for( int j = 0; j < len; j++ )
                likePattern += "0";
        }
        else if( i == level ) {
            if( parent != 0 )
                likePattern += parentData.left(totalLen-len);
            likePattern += "%";
        }
    }

    m_query->bindValue(0,likePattern);
    m_query->exec();

    QList<QTreeWidgetItem*> items;
    bool move = m_query->first();
    while( move ) {
        QString kreg = m_query->value(0).toString();
        if(kreg.compare(parentData)!=0) {
            QString name = m_query->value(1).toString();
            QTreeWidgetItem *item = new QTreeWidgetItem();
            item->setData(0, Qt::DisplayRole, name);
            item->setData(0, Qt::WhatsThisRole, kreg);
            items.append(item);
        }
        move = m_query->next();
    }

    if(parent == 0)
        m_treeWidget->insertTopLevelItems(m_treeWidget->topLevelItemCount(), items);
    else
        parent->insertChildren(parent->childCount(),items);

    if( level < m_pattern.size() ) {
        for( int i = 0; i < items.size(); i++ )        
            recursion(level+1, items.at(i));
    }
}
